package com.btl.component.oss;

import com.btl.component.oss.env.OssProperties;
import com.btl.component.oss.service.OssService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;

import java.net.URI;

@Configuration
@EnableConfigurationProperties(OssProperties.class)
@ConditionalOnClass(OssService.class)
public class AutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public OssService ossService() {
        return new OssService();
    }

    @Bean
    public S3Presigner boatS3Presigner(OssProperties ossProperties) {
        return S3Presigner.builder()
                .region(Region.of(ossProperties.getRegion()))
                .endpointOverride(URI.create(ossProperties.getEndPoint()))
                .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(ossProperties.getAccessKey(), ossProperties.getSecretKey())))
                .build();
    }

    @Bean
    public S3Client boatS3Client(OssProperties ossProperties) {
        return S3Client.builder()
                .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(ossProperties.getAccessKey(), ossProperties.getSecretKey())))
                .region(Region.of(ossProperties.getRegion()))
                .endpointOverride(URI.create(ossProperties.getEndPoint()))
                .serviceConfiguration(S3Configuration.builder()
                        .chunkedEncodingEnabled(true)
                        .build())
                .forcePathStyle(true)
                .build();
    }
}